<!-- 设备管理-设备档案管理-设备备件清单新增页面 -->
<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="设备信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="12">
                <px-form-item label="备件清单名称" prop="inventoryName">
                  <px-input v-model="formValue.inventoryName" clearable placeholder="请输入备件清单名称" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="12">
                <EquipCategorySelect
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  @changeCategory="changeCategory"
                />
              </px-col>
              <px-col :span="12">
                <EquipTypeSelect
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  @changeType="changeType"
                />
              </px-col>
              <px-col :span="12">
                <EquipModelSelect
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  :modelId="formValue.modelId"
                  @changeModel="changeModel"
                />
              </px-col>
            </px-row>
          </px-form>
          <div style="height: 22px; margin-bottom: 16px; font-size: 16px; font-weight: bold; line-height: 22px; color: rgb(0 0 0 / 80%)">
            设备清单
          </div>
          <px-button type="primary" @click="equipDialogVisible = true">选择设备</px-button>
          <px-table :data="formValue.eqpTable" style="margin-bottom: 32px" class="equip-table" size="small" height="240" border>
            <px-table-column type="index" label="序号" width="60" align="center" fixed="left" />
            <px-table-column
              v-for="(item, index) in eqpTableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">
                {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
              </template>
            </px-table-column>
            <px-table-column label="操作" width="120" fixed="right" align="center">
              <template #default="scope">
                <px-tooltip content="移除" placement="top">
                  <px-button link icon="Delete" type="danger" @click="handleEqpDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="关联备品备件">
        <template v-slot:content>
          <div style="height: 22px; margin-bottom: 16px; font-size: 16px; font-weight: bold; line-height: 22px; color: rgb(0 0 0 / 80%)">
            备品备件厂内型号
          </div>
          <px-button type="primary" @click="sparePartsDialogVisible = true">选择厂内型号</px-button>
          <px-table :data="formValue.specTable" style="margin-bottom: 32px" class="equip-table" size="small" height="240" border>
            <px-table-column type="index" label="序号" width="60" align="center" fixed="left" />
            <px-table-column
              v-for="(item, index) in specTableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">
                {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
              </template>
            </px-table-column>
            <px-table-column label="操作" width="120" fixed="right" align="center">
              <template #default="scope">
                <px-tooltip content="移除" placement="top">
                  <px-button link icon="Delete" type="danger" @click="handleSpecDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
          <div style="height: 22px; margin-bottom: 16px; font-size: 16px; font-weight: bold; line-height: 22px; color: rgb(0 0 0 / 80%)">
            当前备品备件清单预览
          </div>
          <px-table :data="formValue.previewTable" style="margin-bottom: 32px" class="equip-table" size="small" height="240" border>
            <px-table-column type="index" label="序号" width="60" align="center" fixed="left" />
            <px-table-column
              v-for="(item, index) in previewTableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">
                {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择设备弹窗 -->
  <EquipIdMultipleSelectDialog
    :dialogVisible="equipDialogVisible"
    :className="formValue.className"
    :categoryId="formValue.categoryId"
    :typeId="formValue.typeId"
    :modelId="formValue.modelId"
    @closeEquipDialog="equipDialogVisible = false"
    @changeEqpIds="changeEqpIds"
  />
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog
    :className="formValue.className"
    :dialogVisible="sparePartsDialogVisible"
    @closeDialog="sparePartsDialogVisible = false"
    @addSpecTable="addSpecTable"
  />
</template>
<script setup lang="ts">
import { addSpareParts, getSpareParts, getSparePartsModelCodesNew } from "@/api/equip/archive";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdMultipleSelectDialog from "@/views/all/equip/components/EquipIdMultipleSelectDialog.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import AddSparePartsDialog from "./AddSparePartsDialog.vue";
import { cloneDeep, isEqual } from "@pureadmin/utils";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "id"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    className: "",
    categoryId: null,
    typeId: null,
    modelId: null,
    eqpTable: [],
    specTable: [],
    previewTable: []
  },
  equipDialogVisible: false,
  sparePartsDialogVisible: false,
  eqpTableColumns: [
    { prop: "eqpId", label: "设备编号", minWidth: "140", showOverflowTooltip: true },
    { prop: "eqpName", label: "设备名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "systemNameAll", label: "系统", minWidth: "140", showOverflowTooltip: true },
    { prop: "categoryName", label: "设备总称", minWidth: "140", showOverflowTooltip: true },
    { prop: "typeName", label: "设备类型", minWidth: "140", showOverflowTooltip: true },
    { prop: "modelName", label: "设备型号", minWidth: "140", showOverflowTooltip: true }
  ],
  specTableColumns: [
    { prop: "typeName", label: "类型", minWidth: "160", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "160", showOverflowTooltip: true }
  ],
  previewTableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "140", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "140", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "140", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "140", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "140", showOverflowTooltip: true }
  ],
  systemCodes: [],
  differContent: null
});
const { formValue, equipDialogVisible, sparePartsDialogVisible, eqpTableColumns, specTableColumns, previewTableColumns, systemCodes, differContent } =
  toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  inventoryName: [{ required: true, message: "备件清单名称不能为空", trigger: "change" }]
}));
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    formValue.value = {
      className: "",
      categoryId: null,
      typeId: null,
      modelId: null,
      eqpTable: [],
      specTable: [],
      previewTable: []
    };
    if (props.drawerType === "edit") {
      getDetail();
    }
  } else {
    formValue.value = {
      className: "",
      eqpTable: [],
      specTable: [],
      previewTable: []
    };
  }
  differContent.value = cloneDeep(formValue.value);
});
// 获取详情
const getDetail = async () => {
  const data = await getSpareParts(props.id);
  formValue.value = data;
  formValue.value.eqpTable = data?.equipmentInfoDTOList || [];
  formValue.value.specTable = data?.sparePartTypeDTOList || [];
  getPreviewTable();
};
// 返回主页面
const backMainPage = () => {
  const differCont = cloneDeep(formValue.value);
  if (isEqual(differContent.value, differCont)) {
    formRef.value?.resetFields();
    differContent.value = null;
    emits("backMainPage");
    return;
  }
  PxMessageBox.confirm("确认退出页面？退出后内容不会保存", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value?.resetFields();
      differContent.value = null;
      emits("backMainPage");
    })
    .catch(() => {});
};
// 选择设备后添加表格数据
const changeEqpIds = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.eqpTable.forEach(item => {
      arr.push(item.eqpId);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.eqpId)) {
        arr2.push(item);
      }
    });
    formValue.value.eqpTable = [...arr2, ...formValue.value.eqpTable];
  }
};
// 选择备件后添加表格数据
const addSpecTable = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.specTable.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        arr2.push(item);
      }
    });
    formValue.value.specTable = [...arr2, ...formValue.value.specTable];
    getPreviewTable();
  }
};
// 删除单条设备
const handleEqpDelete = index => {
  formValue.value.eqpTable.splice(index, 1);
};
// 删除单条备件
const handleSpecDelete = index => {
  formValue.value.specTable.splice(index, 1);
  getPreviewTable();
};
// 备品备件变化、获取新的清单预览
const getPreviewTable = async () => {
  const arr = [];
  if (formValue.value.specTable && formValue.value.specTable.length > 0) {
    formValue.value.specTable.forEach(item => {
      arr.push(item.code);
    });
    const previewTable = await getSparePartsModelCodesNew(arr);
    formValue.value.previewTable = previewTable || [];
  } else {
    formValue.value.previewTable = [];
  }
  differContent.value = cloneDeep(formValue.value);
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.eqpTable && formValue.value.eqpTable.length === 0) {
        PxMessage.error("设备清单不能为空");
        return;
      }
      if (formValue.value.specTable && formValue.value.specTable.length === 0) {
        PxMessage.error("备品备件厂内型号不能为空");
        return;
      }
      const eqpIdList = [];
      const specificationList = [];
      if (formValue.value.eqpTable && formValue.value.eqpTable.length > 0) {
        formValue.value.eqpTable.forEach(item => {
          eqpIdList.push(item.eqpId);
        });
      }
      if (formValue.value.specTable && formValue.value.specTable.length > 0) {
        formValue.value.specTable.forEach(item => {
          specificationList.push(item.code);
        });
      }
      const params = {
        id: formValue.value.id,
        inventoryName: formValue.value.inventoryName,
        className: formValue.value.className,
        categoryId: formValue.value.categoryId,
        typeId: formValue.value.typeId,
        modelId: formValue.value.modelId,
        eqpIdList: eqpIdList,
        specificationList: specificationList
      };
      if (props.drawerType === "add") {
        await addSpareParts(params);
        PxMessage.success("新增设备备件清单成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        params.id = formValue.value.id;
        await addSpareParts(params);
        PxMessage.success("编辑设备备件清单成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["categoryId", "typeId", "modelId"]);
  }
  if (formValue.value.eqpTable && formValue.value.eqpTable.length > 0 && !isOnlyClass) {
    PxMessage.error("科室信息发生变化，设备已被清空，请重新添加！");
    formValue.value.eqpTable = [];
  }
  if (formValue.value.specTable && formValue.value.specTable.length > 0 && !isOnlyClass) {
    PxMessage.error("科室信息发生变化，关联的备品备件已被清空，请重新添加！");
    formValue.value.specTable = [];
    formValue.value.previewTable = [];
  }
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  formValue.value.categoryId = val;
  formRef.value?.resetFields(["typeId", "modelId"]);
  if (formValue.value.eqpTable && formValue.value.eqpTable.length > 0) {
    PxMessage.error("设备总称发生变化，设备已被清空，请重新添加！");
    formValue.value.eqpTable = [];
  }
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val;
  formRef.value?.resetFields(["modelId"]);
  if (formValue.value.eqpTable && formValue.value.eqpTable.length > 0) {
    PxMessage.error("设备类型发生变化，设备已被清空，请重新添加！");
    formValue.value.eqpTable = [];
  }
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val3;
  formValue.value.modelId = val;
  if (formValue.value.eqpTable && formValue.value.eqpTable.length > 0) {
    PxMessage.error("设备型号发生变化，设备已被清空，请重新添加！");
    formValue.value.eqpTable = [];
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
